{% extends 'base.html' %}

{% block head %}
<style>
    /* 页面容器样式 */
    :root {
        --primary-color-rgb: 52, 152, 219;
        --parameter-card-height: auto;
    }
    
    [data-theme="dark"] {
        --primary-color-rgb: 52, 152, 219;
    }
    
    .page-container {
        max-width: 1400px;
        margin: 0 auto;
        padding: 0 20px;
    }
    
    /* 仪表盘布局 - 纵向排列 */
    .parameter-dashboard {
        display: flex;
        flex-direction: column;
        gap: 20px;
        margin-bottom: 20px;
        max-width: 800px;
        margin-left: auto;
        margin-right: auto;
    }
    
    /* 参数卡片样式 */
    .parameter-card {
        background: var(--glass-bg, var(--card-bg));
        backdrop-filter: var(--glass-blur, blur(10px));
        -webkit-backdrop-filter: var(--glass-blur, blur(10px));
        border-radius: var(--border-radius, 16px);
        border: 1px solid rgba(255, 255, 255, 0.1);
        box-shadow: var(--shadow-sm, 0 4px 20px rgba(0, 0, 0, 0.05));
        overflow: hidden;
        height: 100%;
        display: flex;
        flex-direction: column;
        position: relative;
        transition: transform 0.3s ease, box-shadow 0.3s ease;
    }
    
    .parameter-card:hover {
        transform: translateY(-5px);
        box-shadow: var(--shadow, 0 10px 30px rgba(0, 0, 0, 0.08));
    }
    
    /* 卡片头部样式 */
    .parameter-header {
        background: var(--gradient-primary);
        color: white;
        padding: 12px 16px;
        border-top-left-radius: var(--border-radius);
        border-top-right-radius: var(--border-radius);
        display: flex;
        align-items: center;
        position: relative;
        z-index: 1;
    }
    
    .parameter-header::after {
        content: '';
        position: absolute;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        background: rgba(255, 255, 255, 0.1);
        z-index: -1;
        opacity: 0;
        transition: opacity 0.3s ease;
    }
    
    .parameter-card:hover .parameter-header::after {
        opacity: 1;
    }
    
    .parameter-header i {
        margin-right: 12px;
        font-size: 1.2rem;
    }
    
    /* 卡片内容样式 */
    .parameter-body {
        padding: 16px;
        flex: 1;
        display: flex;
        flex-direction: column;
    }
    
    /* 参数卡片容器 */
    .parameter-card-container {
        width: 100%;
    }
    
    /* 参数列表容器 */
    .parameter-list-container {
        width: 100%;
        min-height: 300px;
    }
    
    /* 参数列表样式 */
    .parameter-list {
        height: 100%;
        overflow-y: auto;
        scrollbar-width: thin;
        scrollbar-color: var(--primary-color) var(--bg-secondary);
        padding-right: 5px;
    }
    
    /* 滚动条样式 */
    .parameter-list::-webkit-scrollbar {
        width: 6px;
    }
    
    .parameter-list::-webkit-scrollbar-track {
        background: var(--bg-secondary);
        border-radius: 10px;
    }
    
    .parameter-list::-webkit-scrollbar-thumb {
        background-color: var(--primary-color);
        border-radius: 10px;
    }
    
    /* 参数项样式 */
    .parameter-item {
        display: flex;
        justify-content: space-between;
        align-items: flex-start;
        padding: 12px;
        border-radius: var(--border-radius-sm);
        margin-bottom: 8px;
        background-color: var(--bg-secondary);
        transition: var(--transition);
        border-left: 3px solid transparent;
        position: relative;
        overflow: hidden;
    }
    
    .parameter-item::before {
        content: '';
        position: absolute;
        top: 0;
        left: 0;
        width: 3px;
        height: 100%;
        background: var(--gradient-primary);
        transform: translateX(-100%);
        transition: transform 0.3s ease;
    }
    
    .parameter-item:hover {
        background-color: rgba(var(--primary-color-rgb), 0.08);
        transform: translateX(5px);
    }
    
    .parameter-item:hover::before {
        transform: translateX(0);
    }
    
    .parameter-item:last-child {
        margin-bottom: 0;
    }
    
    .parameter-content {
        flex: 1;
        display: flex;
        flex-direction: column;
        gap: 8px;
    }
    
    /* 参数键样式 */
    .parameter-key {
        font-weight: 600;
        color: var(--primary-color);
        font-size: 1.05rem;
        display: flex;
        align-items: center;
        gap: 8px;
    }
    
    .parameter-key i {
        font-size: 0.9rem;
        opacity: 0.7;
    }
    
    /* 参数值样式 */
    .parameter-value {
        color: var(--text-secondary);
        word-break: break-all;
        font-family: 'Courier New', monospace;
        background-color: rgba(0, 0, 0, 0.05);
        padding: 8px 12px;
        border-radius: 6px;
        font-size: 0.95rem;
        position: relative;
        transition: all 0.3s ease;
    }
    
    .parameter-value:hover {
        background-color: rgba(0, 0, 0, 0.08);
    }
    
    /* 参数操作样式 */
    .parameter-actions {
        display: flex;
        gap: 8px;
        margin-left: 10px;
    }
    
    .parameter-actions button {
        border-radius: 50%;
        width: 36px;
        height: 36px;
        display: flex;
        align-items: center;
        justify-content: center;
        transition: var(--transition);
        background-color: rgba(255, 59, 48, 0.1);
        border: none;
        color: #FF3B30;
    }
    
    .parameter-actions button:hover {
        transform: scale(1.1);
        background-color: rgba(255, 59, 48, 0.2);
    }
    
    /* 表单控件样式 */
    .form-control:focus {
        border-color: var(--primary-color);
        box-shadow: 0 0 0 0.25rem rgba(var(--primary-color-rgb), 0.25);
    }
    
    .input-group-text {
        transition: all 0.3s ease;
    }
    
    .form-control:focus + .input-group-text,
    .form-control:focus ~ .input-group-text {
        border-color: var(--primary-color);
        background-color: rgba(var(--primary-color-rgb), 0.1);
    }
    
    /* 主要按钮样式 */
    .btn-primary {
        background: var(--gradient-primary);
        border: none;
        transition: var(--transition);
        padding: 10px 20px;
    }
    
    .btn-primary:hover {
        transform: translateY(-2px);
        box-shadow: 0 4px 12px rgba(var(--primary-color-rgb), 0.4);
    }
    
    /* 预格式化文本样式 */
    pre {
        background-color: var(--bg-secondary);
        padding: 10px;
        border-radius: var(--border-radius-sm);
        border-left: 4px solid var(--primary-color);
        margin: 0;
        overflow-x: auto;
    }
    
    code {
        font-family: 'Fira Code', 'Courier New', monospace;
        font-size: 0.9rem;
    }
    
    /* 空状态样式 */
    .empty-state {
        text-align: center;
        padding: 40px 20px;
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        height: 100%;
        min-height: 200px;
    }
    
    .empty-state i {
        font-size: 4rem;
        color: var(--text-secondary);
        opacity: 0.3;
        margin-bottom: 20px;
        background: var(--gradient-primary);
        -webkit-background-clip: text;
        -webkit-text-fill-color: transparent;
    }
    
    .empty-state p {
        font-size: 1.2rem;
        color: var(--text-secondary);
        margin-bottom: 8px;
    }
    
    /* 使用提示样式 */
    .usage-tips {
        margin-top: 20px;
        background-color: rgba(var(--primary-color-rgb), 0.05);
        border-radius: var(--border-radius-sm);
        padding: 15px;
        border-left: 3px solid var(--primary-color);
    }
    
    .usage-tips h6 {
        color: var(--primary-color);
        margin-bottom: 10px;
        display: flex;
        align-items: center;
        gap: 8px;
    }
    
    /* 页面图标背景 */
    .page-icon-bg {
        background: var(--gradient-primary);
        opacity: 0.1;
        filter: blur(10px);
    }
    
    .page-icon {
        display: flex;
        align-items: center;
        justify-content: center;
        width: 70px;
        height: 70px;
        border-radius: 50%;
        background: rgba(var(--primary-color-rgb), 0.1);
        margin-bottom: 15px;
    }
    
    /* 参数项淡出动画 */
    .fade-out {
        opacity: 0;
        transform: translateX(20px);
        transition: opacity 0.3s ease, transform 0.3s ease;
    }
    
    /* 暗色模式适配 */
    [data-theme="dark"] .parameter-value {
        background-color: rgba(255, 255, 255, 0.08);
    }
    
    [data-theme="dark"] .parameter-value:hover {
        background-color: rgba(255, 255, 255, 0.12);
    }
    
    [data-theme="dark"] pre {
        background-color: rgba(0, 0, 0, 0.2);
    }
    
    [data-theme="dark"] .usage-tips {
        background-color: rgba(var(--primary-color-rgb), 0.1);
    }
    
    [data-theme="dark"] .parameter-item {
        background: rgba(255, 255, 255, 0.03);
        border-color: rgba(255, 255, 255, 0.05);
    }
    
    [data-theme="dark"] .parameter-item:hover {
        background: rgba(255, 255, 255, 0.06);
    }
    
    /* 动画效果 */
    @keyframes fadeIn {
        from { opacity: 0; transform: translateY(10px); }
        to { opacity: 1; transform: translateY(0); }
    }
    
    .parameter-item {
        animation: fadeIn 0.3s ease forwards;
        animation-delay: calc(var(--index) * 0.05s);
        opacity: 0;
    }
    
    /* 响应式调整 */
    @media (max-width: 768px) {
        .page-container {
            padding: 0 12px;
        }
        
        .parameter-dashboard {
            gap: 15px;
        }
        
        .parameter-list-container {
            height: auto;
            min-height: 200px;
            max-height: 400px;
        }
    }
    
    @media (max-width: 576px) {
        .page-container {
            padding: 0 10px;
        }
        
        .parameter-header {
            padding: 10px 15px;
        }
        
        .parameter-body {
            padding: 15px;
        }
        
        .parameter-item {
            padding: 10px;
            flex-direction: column;
            align-items: flex-start;
        }
        
        .parameter-actions {
            margin-left: 0;
            margin-top: 10px;
            align-self: flex-end;
        }
        
        .page-header h1 {
            font-size: 1.5rem;
        }
        
        .page-header {
            margin-bottom: 20px !important;
        }
    }
</style>
{% endblock %}

{% block content %}
<div class="page-container mt-4 mb-4">
    <!-- 页面标题 -->
    <div class="page-header mb-4 text-center">
        <div class="d-inline-block position-relative mb-2">
            <div class="page-icon-bg position-absolute top-50 start-50 translate-middle rounded-circle" 
                 style="width: 60px; height: 60px; background: var(--gradient-primary); opacity: 0.1; filter: blur(10px);"></div>
            <div class="page-icon position-relative">
                <i class="fas fa-database fa-2x text-primary"></i>
            </div>
        </div>
        <h1 class="h2 fw-bold mb-2">自定义参数管理</h1>
        <p class="text-secondary mx-auto" style="max-width: 600px;">
            创建和管理您的自定义参数，这些参数可以在您的脚本中直接引用，提高代码的可维护性和灵活性。
        </p>
    </div>
    
    <!-- 主要内容区域 -->
    <div class="parameter-dashboard">
        <!-- 添加新参数卡片 -->
        <div class="parameter-card-container">
            <div class="parameter-card">
                <div class="parameter-header">
                    <i class="fas fa-plus-circle"></i>
                    <h5 class="mb-0">添加新参数</h5>
                </div>
                <div class="parameter-body">
                    <form id="add-parameter-form">
                        <div class="mb-3">
                            <label for="parameter-key" class="form-label fw-medium d-flex align-items-center">
                                <i class="fas fa-key me-2 text-primary"></i>
                                参数名称
                            </label>
                            <div class="input-group">
                                <span class="input-group-text bg-light">
                                    <i class="fas fa-tag text-primary"></i>
                                </span>
                                <input type="text" class="form-control" id="parameter-key" name="key" required 
                                       placeholder="输入参数名称" pattern="[A-Za-z0-9_]+">
                            </div>
                            <div class="form-text mt-1 d-flex align-items-start small">
                                <i class="fas fa-info-circle me-2 text-primary mt-1"></i>
                                <span>参数名称只能包含字母、数字和下划线，将用作Python变量名</span>
                            </div>
                        </div>
                        <div class="mb-3">
                            <label for="parameter-value" class="form-label fw-medium d-flex align-items-center">
                                <i class="fas fa-edit me-2 text-primary"></i>
                                参数值
                            </label>
                            <div class="input-group">
                                <span class="input-group-text bg-light">
                                    <i class="fas fa-code text-primary"></i>
                                </span>
                                <input type="text" class="form-control" id="parameter-value" name="value" required 
                                       placeholder="输入参数值">
                            </div>
                        </div>
                        <button type="submit" class="btn btn-primary w-100 py-2 mt-2">
                            <i class="fas fa-save me-2"></i>保存参数
                        </button>
                    </form>
                    
                    <div class="usage-tips mt-3">
                        <h6><i class="fas fa-lightbulb"></i> 提示</h6>
                        <p class="mb-0 small">参数值会自动转换为适当的Python数据类型。例如，<code>123</code>会被转换为整数，<code>true</code>会被转换为布尔值。</p>
                    </div>
                </div>
            </div>
        </div>
        
        <!-- 参数列表卡片 -->
        <div class="parameter-card-container">
            <div class="parameter-card">
                <div class="parameter-header">
                    <i class="fas fa-list"></i>
                    <h5 class="mb-0">当前参数列表</h5>
                </div>
                <div class="parameter-body">
                    <div id="parameters-container" class="parameter-list">
                        {% if parameters %}
                            {% for key, value in parameters.items() %}
                            <div class="parameter-item" data-key="{{ key }}" style="--index: {{ loop.index }}">
                                <div class="parameter-content">
                                    <div class="parameter-key">
                                        <i class="fas fa-hashtag"></i>
                                        {{ key }}
                                    </div>
                                    <div class="parameter-value">{{ value }}</div>
                                </div>
                                <div class="parameter-actions">
                                    <button class="btn delete-parameter" data-key="{{ key }}" title="删除参数">
                                        <i class="fas fa-trash"></i>
                                    </button>
                                </div>
                            </div>
                            {% endfor %}
                        {% else %}
                            <div class="empty-state">
                                <i class="fas fa-database"></i>
                                <p>暂无自定义参数</p>
                                <small class="text-muted">添加参数后将显示在此处</small>
                            </div>
                        {% endif %}
                    </div>
                </div>
            </div>
        </div>
        
        <!-- 使用说明卡片 -->
        <div class="parameter-card-container">
            <div class="parameter-card">
                <div class="parameter-header">
                    <i class="fas fa-info-circle"></i>
                    <h5 class="mb-0">使用说明</h5>
                </div>
                <div class="parameter-body">
                    <p class="mb-2 small">自定义参数将被保存为Python模块，您可以在脚本中通过以下方式引用：</p>
                    <pre><code># 导入特定参数
from user_parameters.{{ username }} import parameter_name

# 或者导入所有参数
from user_parameters.{{ username }} import *

# 然后直接使用参数名
print(parameter_name)  # 将输出对应的参数值</code></pre>
                    
                    <div class="alert alert-info mt-3 d-flex align-items-start p-2">
                        <i class="fas fa-lightbulb me-2 fa-lg mt-1"></i>
                        <div>
                            <strong>小技巧：</strong>
                            <ul class="mt-1 mb-0 small">
                                <li>使用自定义参数可以避免在代码中硬编码配置值</li>
                                <li>适合存储数据库连接信息、API密钥等敏感信息</li>
                                <li>便于在不修改代码的情况下调整脚本行为</li>
                            </ul>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- 确认删除模态框 -->
<div class="modal fade" id="delete-confirm-modal" tabindex="-1">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content">
            <div class="modal-header bg-danger text-white">
                <h5 class="modal-title">
                    <i class="fas fa-exclamation-triangle me-2"></i>确认删除
                </h5>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body p-4">
                <div class="text-center mb-3">
                    <i class="fas fa-trash-alt fa-3x text-danger mb-3"></i>
                    <p class="fs-5">确定要删除参数 <span id="delete-parameter-name" class="fw-bold"></span> 吗？</p>
                    <p class="text-muted">此操作无法撤销，删除后参数将无法恢复。</p>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-outline-secondary" data-bs-dismiss="modal">
                    <i class="fas fa-times me-1"></i>取消
                </button>
                <button type="button" class="btn btn-danger" id="confirm-delete">
                    <i class="fas fa-trash-alt me-1"></i>确认删除
                </button>
            </div>
        </div>
    </div>
</div>

<!-- 操作成功提示 -->
<div class="position-fixed bottom-0 end-0 p-3" style="z-index: 1050">
    <div id="success-toast" class="toast hide" role="alert" aria-live="assertive" aria-atomic="true" data-bs-delay="3000">
        <div class="toast-header bg-success text-white">
            <i class="fas fa-check-circle me-2"></i>
            <strong class="me-auto">操作成功</strong>
            <button type="button" class="btn-close btn-close-white" data-bs-dismiss="toast"></button>
        </div>
        <div class="toast-body">
            <span id="toast-message"></span>
        </div>
    </div>
</div>

<!-- 操作失败提示 -->
<div class="position-fixed bottom-0 end-0 p-3" style="z-index: 1050">
    <div id="error-toast" class="toast hide" role="alert" aria-live="assertive" aria-atomic="true" data-bs-delay="5000">
        <div class="toast-header bg-danger text-white">
            <i class="fas fa-exclamation-circle me-2"></i>
            <strong class="me-auto">操作失败</strong>
            <button type="button" class="btn-close btn-close-white" data-bs-dismiss="toast"></button>
        </div>
        <div class="toast-body">
            <span id="error-message"></span>
        </div>
    </div>
</div>

<script>
    document.addEventListener('DOMContentLoaded', function() {
        // 初始化Toast组件
        const successToast = new bootstrap.Toast(document.getElementById('success-toast'));
        const errorToast = new bootstrap.Toast(document.getElementById('error-toast'));
        
        // 显示成功消息
        function showSuccess(message) {
            document.getElementById('toast-message').textContent = message;
            successToast.show();
        }
        
        // 显示错误消息
        function showError(message) {
            document.getElementById('error-message').textContent = message;
            errorToast.show();
        }
        
        // 添加参数表单提交
        const addParameterForm = document.getElementById('add-parameter-form');
        const keyInput = document.getElementById('parameter-key');
        const valueInput = document.getElementById('parameter-value');
        const parametersContainer = document.getElementById('parameters-container');
        
        addParameterForm.addEventListener('submit', function(e) {
            e.preventDefault();
            
            // 禁用表单，显示加载状态
            const submitBtn = this.querySelector('button[type="submit"]');
            const originalBtnText = submitBtn.innerHTML;
            submitBtn.disabled = true;
            submitBtn.innerHTML = '<span class="spinner-border spinner-border-sm me-2" role="status" aria-hidden="true"></span>保存中...';
            
            const key = keyInput.value.trim();
            const value = valueInput.value.trim();
            
            fetch('/api/custom_parameters', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({ key, value }),
            })
            .then(response => response.json())
            .then(data => {
                // 恢复按钮状态
                submitBtn.disabled = false;
                submitBtn.innerHTML = originalBtnText;
                
                if (data.success) {
                    // 清空表单
                    keyInput.value = '';
                    valueInput.value = '';
                    showSuccess(`参数 ${key} 添加成功！`);
                    
                    // 动态添加新参数到列表而不刷新页面
                    const emptyState = parametersContainer.querySelector('.empty-state');
                    if (emptyState) {
                        emptyState.remove();
                    }
                    
                    // 获取当前参数数量作为索引
                    const itemCount = parametersContainer.querySelectorAll('.parameter-item').length;
                    
                    // 创建新的参数项
                    const newItem = document.createElement('div');
                    newItem.className = 'parameter-item';
                    newItem.setAttribute('data-key', key);
                    newItem.style.setProperty('--index', itemCount + 1);
                    
                    newItem.innerHTML = `
                        <div class="parameter-content">
                            <div class="parameter-key">
                                <i class="fas fa-hashtag"></i>
                                ${key}
                            </div>
                            <div class="parameter-value">${value}</div>
                        </div>
                        <div class="parameter-actions">
                            <button class="btn delete-parameter" data-key="${key}" title="删除参数">
                                <i class="fas fa-trash"></i>
                            </button>
                        </div>
                    `;
                    
                    parametersContainer.appendChild(newItem);
                    
                    // 为新添加的删除按钮添加事件监听
                    const newDeleteButton = newItem.querySelector('.delete-parameter');
                    newDeleteButton.addEventListener('click', function() {
                        parameterToDelete = this.getAttribute('data-key');
                        document.getElementById('delete-parameter-name').textContent = parameterToDelete;
                        deleteModal.show();
                    });
                } else {
                    showError('添加参数失败: ' + data.message);
                }
            })
            .catch(error => {
                console.error('Error:', error);
                submitBtn.disabled = false;
                submitBtn.innerHTML = originalBtnText;
                showError('添加参数失败，请检查网络连接');
            });
        });
        
        // 删除参数
        const deleteButtons = document.querySelectorAll('.delete-parameter');
        const deleteModal = new bootstrap.Modal(document.getElementById('delete-confirm-modal'));
        let parameterToDelete = '';
        
        deleteButtons.forEach(button => {
            button.addEventListener('click', function() {
                parameterToDelete = this.getAttribute('data-key');
                document.getElementById('delete-parameter-name').textContent = parameterToDelete;
                deleteModal.show();
            });
        });
        
        document.getElementById('confirm-delete').addEventListener('click', function() {
            // 禁用按钮，显示加载状态
            const deleteBtn = this;
            const originalBtnText = deleteBtn.innerHTML;
            deleteBtn.disabled = true;
            deleteBtn.innerHTML = '<span class="spinner-border spinner-border-sm me-2" role="status" aria-hidden="true"></span>删除中...';
            
            fetch(`/api/custom_parameters/${parameterToDelete}`, {
                method: 'DELETE',
            })
            .then(response => response.json())
            .then(data => {
                // 恢复按钮状态
                deleteBtn.disabled = false;
                deleteBtn.innerHTML = originalBtnText;
                
                if (data.success) {
                    // 关闭模态框
                    deleteModal.hide();
                    showSuccess(`参数 ${parameterToDelete} 已成功删除！`);
                    
                    // 移除对应的参数项
                    const paramItem = document.querySelector(`.parameter-item[data-key="${parameterToDelete}"]`);
                    if (paramItem) {
                        paramItem.classList.add('fade-out');
                        setTimeout(() => {
                            paramItem.remove();
                            
                            // 检查是否还有参数，如果没有则显示空状态
                            const paramItems = document.querySelectorAll('.parameter-item');
                            if (paramItems.length === 0) {
                                const emptyState = document.createElement('div');
                                emptyState.className = 'empty-state';
                                emptyState.innerHTML = `
                                    <i class="fas fa-database"></i>
                                    <p>暂无自定义参数</p>
                                    <small class="text-muted">添加参数后将显示在此处</small>
                                `;
                                parametersContainer.appendChild(emptyState);
                            } else {
                                // 更新剩余参数项的索引
                                paramItems.forEach((item, index) => {
                                    item.style.setProperty('--index', index + 1);
                                });
                            }
                        }, 300);
                    } else {
                        // 如果找不到元素，刷新页面
                        setTimeout(() => {
                            window.location.reload();
                        }, 1000);
                    }
                } else {
                    showError('删除参数失败: ' + data.message);
                }
            })
            .catch(error => {
                console.error('Error:', error);
                deleteBtn.disabled = false;
                deleteBtn.innerHTML = originalBtnText;
                showError('删除参数失败，请检查网络连接');
            });
        });
    });
</script>
{% endblock %}